package com.dmzc.stage2.chapter19;

public class FutureTask<T> implements Future<T> {
    //计算结果
    private T result;
    private boolean isDone = false;
    private final Object LOCK = new Object();

    /**
     * 返回计算后的结果，该方法会陷入阻塞状态
     *
     * @return
     * @throws InterruptedException
     */
    @Override
    public T get() throws InterruptedException {
        synchronized (LOCK) {
            while (!isDone) {
                LOCK.wait();
            }
        }
        return result;
    }

    /**
     * 判断任务是否已经被执行完成
     *
     * @return
     */
    @Override
    public boolean done() {
        return isDone;
    }

    protected void finish(T result) {
        synchronized (LOCK) {
            if (isDone)
                return;
            this.result = result;
            this.isDone = true;
            LOCK.notifyAll();
        }
    }
}
